package com.barradata.common.utils

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

import java.util.Timer
import java.util.TimerTask
import java.util.regex.Matcher
import java.util.regex.Pattern


/**
 * Created by WuNan-QF on 16/7/14.
 */
object EditTextUtils {
    fun getString(editText: EditText): String {
        return editText.text.toString()
    }

    fun getTrimString(editText: EditText): String {
        return replaceBlank(editText.text.toString())
    }

    fun hideKeyboard(context: Activity) {
        hideKeyboard(context, ViewUtil.getRootView(context))
    }

    fun hideKeyboard(context: Context, rootView: View) {
        val imm = rootView.context.getSystemService(Context
                .INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
            imm.hideSoftInputFromWindow(rootView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    fun focusDisable(editText: EditText) {
        editText.isFocusable = false
        editText.isFocusableInTouchMode = false
    }

    fun focusEnable(editText: EditText) {
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
    }

    fun showInputMethod(editText: EditText) {
        focusEnable(editText)
        editText.requestFocus()
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                val inputManager = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager.showSoftInput(editText, 0)
            }

        },
                998)
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符
     *
     * @param str
     * @return
     */
    fun replaceBlank(str: String?): String {
        var dest = ""
        if (str != null) {
            val p = Pattern.compile("\\s*|\t|\r|\n")
            val m = p.matcher(str)
            dest = m.replaceAll("")
        }
        return dest
    }

}
